/*
 * UserNet  --  TCP/IP implementation in userspace
 * Copyright (C) 2010  Robert Millan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <pthread.h>

#include "unet/dev.h"
#include "unet/misc.h"

static struct unet_device *device_list[16];
static unsigned int device_count;
static pthread_mutex_t device_list_mutex = PTHREAD_MUTEX_INITIALIZER;

void
unet_device_add (struct unet_device *device)
{
  pthread_mutex_lock (& device_list_mutex);

  device->id = device_count++;
  device->next = HASH_HEAD (device_list, device->id);
  HASH_HEAD (device_list, device->id) = device;

  pthread_mutex_unlock (& device_list_mutex);
}

struct unet_device *
unet_device_find (uint32_t id)
{
  struct unet_device *i;
  for (i = HASH_HEAD (device_list, id); i; i = i->next)
    if (i->id == id)
      return i;

  return NULL;
}

struct unet_device *
unet_device_iterate (int (*hook) (struct unet_device *device))
{
  int i;
  struct unet_device *j;
  for (i = 0; i < ARRAY_SIZE (device_list); i++)
    for (j = device_list[i]; j; j = j->next)
      if (hook (j))
	return j;

  return NULL;
}

int
unet_device_count ()
{
  return device_count;
}
